package com.crt.nexus.security.util;

import com.crt.nexus.security.jwt.JoseHeader;
import com.crt.nexus.security.jwt.JwtClaimsSet;
import lombok.experimental.UtilityClass;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;

import java.time.Instant;
import java.util.List;
import java.util.Map;

@UtilityClass
public class JwtUtils {

    public JoseHeader.Builder headers() {
        return JoseHeader.withAlgorithm(SignatureAlgorithm.RS256);
    }

    public JwtClaimsSet.Builder accessTokenClaims(String id, String subject, String clientId, Integer validSeconds, Map<String, Object> additionals) {
        Instant issuedAt = Instant.now();
        Instant expiresAt = issuedAt.plusSeconds(validSeconds);
        // @formatter:off
        JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder();
        claimsBuilder
                .id(id)
                .subject(subject)
                .client(clientId)
                .issuedAt(issuedAt)
                .expiresAt(expiresAt);
        additionals.forEach((key, value) -> {
            if (value != null) {
                claimsBuilder.claim(key, value);
            }
        });
        // @formatter:on
        return claimsBuilder;
    }


    public JwtClaimsSet.Builder refreshTokenClaims(String id, String ati, String subject, String clientId, Integer validSeconds, Map<String, Object> additionals) {
        Instant issuedAt = Instant.now();
        Instant expiresAt = issuedAt.plusSeconds(validSeconds);
        // @formatter:off
        JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder();
        claimsBuilder
                .id(id)
                .ati(ati)
                .subject(subject)
                .client(clientId)
                .issuedAt(issuedAt)
                .expiresAt(expiresAt);
        additionals.forEach((key, value) -> {
            if (value != null) {
                claimsBuilder.claim(key, value);
            }
        });
        // @formatter:on
        return claimsBuilder;
    }

}
